const router = require("koa-router")();
const DB = require("../../module/db");
const sd = require("silly-datetime");
const rest = require('restler');

router.get("/", async (ctx) => {
    ctx.body = "cgTask首页";

}).post("/addProject", async (ctx) => {    //教师创建作业
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm')
    let access_token = ctx.request.body.access_token    //教师的token
    let name = ctx.request.body.name    //作业名称
    let intro = ctx.request.body.introduction   //作业说明

    let teacherId
    let cg_uri = 'http://cgyun.cn';

    const add = new Promise((resolve) => {
        let url2 = cg_uri + '/auth/v1/users/get?'
        rest.post(url2, {
            data: {
                "access_token": access_token
            }
        }).on('complete',async function (result) {
            console.log("result2:", result)
            let username = result.data.username
            let user = await DB.find('user', {"username": username})

            if (user.length === 0) {
                let userData = {}
                userData['access_token'] = access_token
                userData['team'] = 'cgyun'
                userData['alias'] = result.data.name
                userData['username'] = result.data.username
                userData['password'] = ''
                userData['teamName'] = ''
                userData['teamAlias'] = ""
                userData['role'] = ""
                userData['enable'] = 'true'
                userData['createDate'] = new Date()
                userData['photoFileID'] = ''
                userData['__v'] = '0'

                //第三次请求
                let url3 = cg_uri + '/cg/v1/team/authenticate'
                let client_id = 'shannewsightcgverify'
                rest.post(url3, {
                    headers: {
                        "Authorization": "Bearer " + userData['access_token']
                    },
                    data: {
                        "client_id": client_id,
                        "resource_group": 'CGTEAM',
                    }
                }).on('complete',async function (result) {
                    console.log("result3:", result)
                    userData['teamName'] = result.teamName
                    userData['teamAlias'] = result.teamAlias
                    userData['role'] = result.data

                    const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
                    let dataInsertResult = await DB.insert('user', userData);
                    if (dataInsertResult.result.ok) {
                        console.log(time + "：添加用户成功" + userData.username);
                    } else {
                        console.log(time + "：插入失败");
                    }

                    teacherId = dataInsertResult.ops[0]._id.toString()
                    let list = await addProject(name, teacherId, intro)
                    resolve(list)
                })
            } else {
                teacherId = user[0]._id.toString()
                let list = await addProject(name, teacherId, intro)
                resolve(list)
            }
        })
    });
    await add.then(data => {
        if (data.flag) {
            console.log(time + "：添加作业成功" + ctx.request.body.name);
            ctx.body = {
                status: "success",
                info: data.info  //返回作业id
            }
        } else {
            ctx.body = {
                status: "error",
                info: "添加作业失败"
            };
        }
    })

}).post("/addTask", async (ctx) => {   //学生查看作业
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm')
    let access_token = ctx.request.body.access_token    //学生的token
    let projectId = ctx.request.body.projectId    //作业id
    let callbackUrl = ctx.request.body.callbackUrl

    let studentId, studentName, stuProId

    let cg_uri = 'http://cgyun.cn';

    const add = new Promise(resolve => {
        let url2 = cg_uri + '/auth/v1/users/get?'
        rest.post(url2, {
            data: {
                "access_token": access_token
            }
        }).on('complete',async function (result) {
            console.log("result2:", result)
            let username = result.data.username
            let user = await DB.find('user', {"username": username})

            if (user.length === 0) {
                let userData = {}
                userData['access_token'] = access_token
                userData['team'] = 'cgyun'
                userData['alias'] = result.data.name
                userData['username'] = result.data.username
                userData['password'] = ''
                userData['teamName'] = ''
                userData['teamAlias'] = ""
                userData['role'] = ""
                userData['enable'] = 'true'
                userData['createDate'] = new Date()
                userData['photoFileID'] = ''
                userData['__v'] = '0'

                //第三次请求
                let url3 = cg_uri + '/cg/v1/team/authenticate'
                let client_id = 'shannewsightcgverify'
                rest.post(url3, {
                    headers: {
                        "Authorization": "Bearer " + userData['access_token']
                    },
                    data: {
                        "client_id": client_id,
                        "resource_group": 'CGTEAM',
                    }
                }).on('complete',async function (result) {
                    console.log("result3:", result)
                    userData['teamName'] = result.teamName
                    userData['teamAlias'] = result.teamAlias
                    userData['role'] = result.data

                    const time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
                    let dataInsertResult = await DB.insert('user', userData);
                    if (dataInsertResult.result.ok) {
                        console.log(time + "：添加用户成功" + userData.username);
                    } else {
                        console.log(time + "：插入失败");
                    }
                    // console.log(dataInsertResult.ops[0]._id)

                    let list = {
                        "name": "我的作业",
                        "userId": dataInsertResult.ops[0]._id.toString(),
                        "reviews": [],
                        "introduction": "我的作业列表",
                        "collections": [],
                    }
                    let addProjectResult = await DB.insert('project', list);
                    if (addProjectResult.result.ok) {
                        console.log(time + "：添加项目成功" + list.name);
                        studentId = dataInsertResult.ops[0]._id.toString()
                        studentName = userData.username
                        stuProId = addProjectResult.ops[0]._id.toString()
                        let list = await addTask(projectId, studentName, studentId, stuProId, callbackUrl)
                        resolve(list)

                        // if (list.flag) {
                        //     console.log(time + "：" + studentName + "学生添加作业成功")
                        //     ctx.body = {
                        //         status: "success",
                        //         info: list.info  //返回学生作业id
                        //     };
                        // } else {
                        //     ctx.body = {
                        //         status: "error",
                        //         info: "添加作业失败"
                        //     };
                        // }
                    } else {
                        console.log(time + "：添加项目失败")
                    }
                })
            } else {
                studentId = user[0]._id.toString()
                studentName = user[0].username
                let data2 = await DB.find('project', {"userId": studentId})
                stuProId = data2[0]._id.toString()
                let list = await addTask(projectId, studentName, studentId, stuProId, callbackUrl)
                resolve(list)
            }
        });
    })

    await add.then(data => {
        if (data.flag) {
            console.log(time + "：" + studentName + "学生添加作业成功")
            ctx.body = {
                status: "success",
                info: data.info  //返回学生作业id
            };
        } else {
            ctx.body = {
                status: "error",
                info: "添加作业失败"
            };
        }
    })

}).post("/submitStatus", async (ctx) => {
    let remote_task_id = ctx.request.body.remote_task_id
    let action = ctx.request.body.action
    let score = ctx.request.body.score
    let url = ctx.request.body.url

    const submit = new Promise(resolve => {
        rest.post(url, {
            headers: {
                'Content-Type': 'x-www-form-urlencoded',
            },
            data: {
                "remote_task_id": remote_task_id,
                "action": action,
                "score": score
            }
        }).on('complete', function (result) {
            console.log("submitStatusResult:", result)
            // userData['team'] = result.team
            resolve(result)
        })
    })
    await submit.then(data => ctx.body = data)

});

async function addProject(name, teacherId, intro) {
    let list = {
        "name": name,
        "userId": teacherId,
        "reviews": [],
        "collections": [],
        "introduction": intro
    }
    let result = await DB.insert('project', list);
    return {
        "flag": result.result.ok,
        "info": result.ops[0]._id.toString()
    }
}

async function addTask(projectId, studentName, studentId, stuProId, callbackUrl) {
    let project = await DB.find('project', {"_id": DB.getObjectId(projectId)})
    let proName = project[0].name.toString()

    let data3 = await DB.find('review', {"name": studentName, "projectName": proName})
    if (data3.length === 0){
        let list = {
            "name": studentName,
            "userId": [studentId],
            "mediaId": [],
            "introduction": "",
            "link": '',
            "callbackUrl": callbackUrl,
            "projectName": proName,
        }
        let result1 = await DB.insert('review', list);
        let result2 = await DB.addArray("project", {"_id": DB.getObjectId(projectId)}, {"reviews": result1.ops[0]._id})
        let result4 = await DB.addArray("project", {"_id": DB.getObjectId(stuProId)}, {"reviews": result1.ops[0]._id})
        let result3 = await DB.update("review", {"_id": DB.getObjectId(result1.ops[0]._id)}, {"link": cryptId(result1.ops[0]._id.toString())})

        return {
            "flag": result1.result.ok && result2.result.ok && result3.result.ok && result4.result.ok,
            "info": result1.ops[0]._id.toString()
        }
    } else {
        return {
            "flag": true,
            "info": data3[0]._id.toString()
        }
    }
}

module.exports = router.routes();
